import React, {useState, useEffect}from 'react';

export default function TodoItem(type) {
    const [todoList, setTodo] = useState([{
        id:1,
        title:"完成工作",
        completed:false
    },{
        id:2,
        title:"学习",
        completed:false
    },{
        id:3,
        title:"锻炼",
        completed:false
    }])

    useEffect(() => {
        console.log(type.type)
        if(type.type === 1) {
            let url = `https://jsonplaceholder.typicode.com/todos/`
            console.log(url)
            fetch(url).then(res => {
                return res.json()
            }).then(data => {setTodo(data)})
        } 
        
    }, [type])

    function handleComplete(todo) {
        const newList = todoList.map(t => {
            if(t.id === todo.id) {
                return {...t, completed:!t.completed};
            }
            return t;
        });
        setTodo(newList);
    }

    function handleclick(id) {
        const newList = todoList.filter(td => td.id !== id)
        setTodo(newList)
    }

    return (
        <div style={{marginTop: 20 }}>
                <ul style={{textAlign:'left'}}>
                {
                todoList.map(todo => (
                    <li key={todo.id}>
                        <input type="checkbox" checked={todo.completed} onChange={(ev) => {
                            handleComplete(todo)
                        }} />
                        {todo.title}：{todo.completed? '已完成':'未完成'}
                        <button style={{ marginLeft: 20 }} onClick={() => {
                            handleclick(todo.id)
                        }} >删除</button>
                    </li>
                ))
                }
            </ul>
        </div>
        
    );
}